<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="750px" :clickModalClose="true"
            @confirm="handleSubmit" @close="handleClose" :cancelButtonText="cancelButtonText"
            :confirmButtonText="confirmButtonText">
            <el-form ref="formRef" :model="formData" label-width="130px" :rules="formRules">
                <el-form-item label="优惠券名称" prop="name">
                    <el-input v-model="formData.name" :readonly="ifinfo" />
                </el-form-item>

                <el-form-item label="优惠券对应的商品" prop="service">
                    <el-select v-model="formData.service" placeholder="请选择优惠券对应的商品" multiple filterable
                        @change="changeservice" @blur="changeservice" @clear="changeservice"
                        :disabled="selectStateservice2 || ifinfo" clearable style="width: 100%;">
                        <el-option v-for="(item, index) in splbList" :key="index" :label="item.name" :value="item.id">
                            <span style="float: left">{{ item.goodsName }}</span>
                            <span style="
                float: right;
                color: var(--el-text-color-secondary);
                font-size: 13px;
                ">
                                {{ item.name }}
                            </span>
                        </el-option>

                    </el-select>
                </el-form-item>
                <el-form-item label="优惠价格" prop="amount">
                    <el-input-number v-model="formData.amount" :min="1" :readonly="ifinfo" />
                </el-form-item>
                <el-form-item label="发放优惠券数量" prop="number">
                    <el-input-number v-model="formData.number" :min="1" :readonly="ifinfo" />
                </el-form-item>
                <el-form-item label="使用范围" prop="useRange">
                    {{ formData.useRange }}
                    <el-select v-model="formData.useRange" placeholder="请选择使用范围"
                        :disabled="selectStateservice || ifinfo" @change="changeservice2" @blur="changeservice2"
                        @clear="changeservice2" clearable>
                        <el-option v-for="(item, index) in typeList" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="是否叠加" prop="isSuperimposing">
                    <el-select v-model="formData.isSuperimposing" placeholder="请选择是否叠加" :disabled="ifinfo">
                        <el-option :key="0" label="不叠加使用" :value="0" />
                        <el-option :key="1" label="叠加使用" :value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="分享类型" prop="shareType">
                    <el-select v-model="formData.shareType" placeholder="请选择分享类型" :disabled="ifinfo">
                        <el-option :key="0" label="不分享" :value="0" />
                        <el-option :key="1" label="二维码分享" :value="1" />
                        <el-option :key="2" label="兑换码分享" :value="2" />
                        <el-option :key="2" label="二维码分享一张优惠券" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item label="图片地址" prop="imageAddress">
                    <el-upload v-model:file-list="fileList" class="upload-demo"
                        :action="apiUrl + 'api/common/upload/image'" multiple :on-preview="handlePreview"
                        :on-remove="handleRemove" :before-remove="beforeRemove" :on-exceed="handleExceed"
                        :on-success="successFile" :limit="52428800" :headers="headers"
                        :disabled="ifinfo"><!-- :limit="3" -->
                        <el-button type="primary">点击上传</el-button>
                        <template #tip>
                            <div class="el-upload__tip">文件大小限制为 50mb.</div>
                        </template>
                    </el-upload>
                    <!--  <el-input v-model="formData.imageAddress" /> -->
                </el-form-item>
                <el-form-item label="是否免费" prop="isGratis">
                    <el-select v-model="formData.isGratis" placeholder="请选择是否叠加" :disabled="ifinfo">
                        <el-option :key="0" label="不免费" :value="0" />
                        <el-option :key="1" label="免费" :value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="优惠券开始时间" prop="startTime">
                    <el-date-picker :readonly="ifinfo" v-model="formData.startTime" type="datetime"
                        placeholder="请选择日期时间" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="优惠券结束时间" prop="endTime">
                    <el-date-picker :readonly="ifinfo" v-model="formData.endTime" type="datetime" placeholder="请选择日期时间"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="兑换码" prop="" v-if="ifinfo">
                    <el-card style="width: 100%; max-height: 150px; overflow: auto" v-if="taglist" class="tagList">
                        <el-tag style="margin-bottom: 10px; margin-right: 10px" v-for="(item, index) in taglist"
                            :key="index" type="primary">{{ item }}</el-tag>
                    </el-card>
                    <!--  {{ formData }} -->
                </el-form-item>
                <el-form-item label="优惠券说明" prop="content">
                    <el-input v-model="formData.content" type="textarea" :readonly="ifinfo" />
                </el-form-item>
            </el-form>
            <el-table v-if="tableData" :data="tableData" style="width: 100%">
                <el-table-column prop="username" label="用户名称" />
                <el-table-column prop="useTime" label="使用时间" />
                <el-table-column prop="isUsed" label="是否使用">
                    <template #default="scope">
                        <el-tag v-if="scope.row.isUsed == 0" type="success">未使用</el-tag>
                        <el-tag v-if="scope.row.isUsed == 1" type="danger">已使用</el-tag>
                    </template>
                </el-table-column>
            </el-table>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from "element-plus";

import type Popup from "@/components/popup/index.vue";
import feedback from "@/utils/feedback";
import type { PropType } from "vue";
import {
    getcategoryapi,
    getcsdetailapi,
    getcgoodslistapi,
    getcouponEdit,
    getlcouponAdd,
} from "@/api/service/discountCoupon";
import { ElMessage, ElMessageBox } from "element-plus";

import type { UploadProps, UploadUserFile } from "element-plus";
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({}),
    },
    serviceList: {
        type: Array,
        default: [{ name: 1, id: 1 }],
    },
});
const emit = defineEmits(["success", "close"]);
const apiUrl = `${import.meta.env.VITE_APP_BASE_URL || ""}/`;
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const mode = ref("add");
const popupTitle = computed(() => {
    return mode.value == "edit"
        ? "编辑优惠券"
        : mode.value == "info"
            ? "详情"
            : "新增优惠券";
});
const cancelButtonText = ref("取消");
const confirmButtonText = ref("确定");
const ifinfo = ref(false);
const formData: any = reactive({
    id: null,
    name: null,
    service: null || [],
    amount: null,
    number: null,
    useRange: null,
    isSuperimposing: null,
    shareType: null,
    imageAddress: null,
    startTime: null,
    endTime: null,
    useTime: 0,
    conditions: 0,
    claim: 0,
    content: null,
    isGratis: 0
});

const formRules = {
    id: [
        {
            required: true,
            message: "请输入规格ID，随机生成的唯一ID",
            trigger: ["blur"],
        },
    ],
    goodsId: [
        {
            required: true,
            message: "请输入服务名称",
            trigger: ["blur"],
        },
    ],
    name: [
        {
            required: true,
            message: "请输入规格名称",
            trigger: ["blur"],
        },
    ],
    /* price: [
      {
        required: true,
        message: "请输入价格，表示该规格的价格",
        trigger: ["blur"],
      },
    ], */
    //   incrementPrice: [
    //     {
    //       required: true,
    //       message: "请输入数量递增价格，如果为空表示不递增",
    //       trigger: ["blur"],
    //     },
    //   ],
    /*  createdBy: [
      {
        required: true,
        message: "请输入创建人",
        trigger: ["blur"],
      },
    ],
    updatedBy: [
      {
        required: true,
        message: "请输入修改人",
        trigger: ["blur"],
      },
    ], */
    //   remark: [
    //     {
    //       required: true,
    //       message: "请输入备注",
    //       trigger: ["blur"],
    //     },
    //   ],
};

const handleSubmit = async () => {
    await formRef.value?.validate();
    //   const data: any = { ...formData };
    const data = {};
    for (const key in formData) {
        if (formData[key] != null) {
            data[key] = formData[key];
        }
    }
    data;
    mode.value == "edit" ? await getlcouponAdd(data) : await getcouponEdit(data);
    popupRef.value?.close();
    feedback.msgSuccess("操作成功");
    emit("success");
};

const open = (type: any) => {
    if (type == "info") {
        cancelButtonText.value = "";
        confirmButtonText.value = "";
        ifinfo.value = true;
    } else {
        cancelButtonText.value = "取消";
        confirmButtonText.value = "确定";
    }
    mode.value = type;
    popupRef.value?.open();
};
const infoForm: any = ref(null);
const taglist: any = ref(null);
const tableData: any = ref(null);
const setFormData = async (data: Record<string, any>) => {
    if (mode.value == "info") {
        console.log(data);
        console.log("data");

        infoForm.value = data;
        taglist.value = infoForm.value.couponCodes;
        tableData.value = infoForm.value.useUser;
        console.log(infoForm.value.couponCodes);
        console.log(JSON.stringify(infoForm.value.couponCodes));
    }
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            if (key == "service") {
                formData[key] = JSON.parse(data[key]);
                if (JSON.parse(data[key]) != null || JSON.parse(data[key]) > 0) {
                    selectStateservice.value = true;
                    formData.useRange = null;
                } else {
                    selectStateservice.value = false;
                }
            } else {
                formData[key] = data[key];
            }
        }
    }
};

const getDetail = async (row: Record<string, any>) => {
    console.log("row");
    console.log(row);
    const data = await getcsdetailapi(row.id);
    setFormData(data);
};

const handleClose = () => {
    emit("close");
};

const typeList: any = ref([]);
const splbList: any = ref([]);
onMounted(async () => {
    typeList.value = await getcategoryapi({});
    let res = await getcgoodslistapi({
        pageNo: 1,
        pageSize: 999,
        name: "",
        status: 1,
        categoryId: "",
    });

    splbList.value = res.lists;
});
defineExpose({
    open,
    setFormData,
    getDetail,
});

const fileList = ref<UploadUserFile[]>([]);

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
    console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
    console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
    ElMessage.warning(
        `上传数量的限制是3，您选择了 ${files.length} 文件，加起来等于 ${files.length + uploadFiles.length
        } `
    );
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(`是否取消上传 ${uploadFile.name} ?`).then(
        () => true,
        () => false
    );
};

const successFile: UploadProps["onSuccess"] = (response, uploadFile) => {
    formData.imageAddress = response.data.path;
};

import { clearAuthInfo, getToken } from "@/utils/auth";

const headers = {
    Token: getToken() || "", // Replace with your actual token
};
const selectStateservice = ref(false);
const selectStateservice2 = ref(false);
const changeservice = () => {
    if (
        JSON.stringify(formData.service) == "[]" ||
        JSON.stringify(formData.service) == []
    ) {
        selectStateservice.value = false;
    } else {
        selectStateservice.value = true;
        formData.useRange = null;
    }
};

const changeservice2 = () => {
    if (formData.useRange != "") {
        selectStateservice2.value = true;
        console.log(formData.useRange);
        formData.service = [];
    } else {
        selectStateservice2.value = false;
        console.log(formData.useRange);
    }
};
</script>
<style lang="scss" scoped>
/* 滚动条整体样式 */
.tagList::-webkit-scrollbar {
    width: 10px;
    /* 设置滚动条宽度 */
}

/* 滚动条滑块 */
.tagList::-webkit-scrollbar-thumb {
    background-color: #ecf5ff;
    /* 默认白色主题下的颜色 */
    border-radius: 10px;
    /* 设置滑块圆角 */
}

/* 滚动条轨道 */
.tagList::-webkit-scrollbar-track {
    background: transparent;
    /* 设置轨道背景色 */
}

/* 黑色主题下滚动条颜色变化 */
.ruyiplus-dark .tagList::-webkit-scrollbar-thumb {
    background-color: #262727;
    /* 黑色主题下的颜色 */
}
</style>